﻿function getNoticeListPanel() {
	var pageSize = 10;

	var store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : url.getNoticeList
						}),
				reader : new Ext.data.JsonReader({
							root : 'result',
							totalProperty : 'total',
							id : 'nid'
						}, ['nid', 'title', 'color', 'time'])
			});
	store.load({
				params : {
					start : 0,
					limit : pageSize
				}
			});

	var cm = new Ext.grid.ColumnModel([{
				header : 'Title',
				sortable : false,
				dataIndex : 'title',
				renderer : titleFormat
			}]);

	var sm = new Ext.grid.RowSelectionModel({
				singleSelect : true
			});

	var pagebar = new Ext.PagingToolbar({
				pageSize : pageSize,
				store : store
			});

	var grid = new Ext.grid.GridPanel({
				region : 'center',
				loadMask : {
					msg : '载入中...'
				},
				viewConfig : {
					forceFit : true
				},
				store : store,
				cm : cm,
				sm : sm,
				bbar : pagebar,
				hideHeaders : true
			});

	if (sys.god) {
		var menu = new Ext.menu.Menu({
					items : [{
								text : '添加',
								iconCls : 'add-icon',
								handler : onAdd
							}, {
								text : '编辑',
								iconCls : 'edit-icon',
								handler : onEdit
							}, {
								text : '删除',
								iconCls : 'delete-icon',
								handler : onDelete
							}]
				});
		grid.on('contextmenu', function(e) {
					e.preventDefault();
					var rowIndex = grid.getView().findRowIndex(e.getTarget());
					if (Ext.isNumber(rowIndex))
						sm.selectRow(rowIndex);
					else
						sm.clearSelections();
					var record = getSelect();
					menu.get(1).setDisabled(!record);
					menu.get(2).setDisabled(!record);
					menu.showAt(e.getXY());
				});
	}
	return grid;

	function titleFormat(value, p, record) {
		return String
				.format(
						'<a href="javascript:void(0);" onclick="showNotice({1});" title="{2} ({4})" style="color:{3}" class="likelink">{0}</a>&nbsp;&nbsp; <span style="color:#CCCCCC">({4})</span>',
						value, record.data.nid, record.data.title, record.data.color,
						record.data.time);
	}
	function getSelect() {
		if (sm.getCount() == 0) return null;
		return sm.getSelected();
	}

	function onAdd() {
		addOrEditNotice();
	}
	function onEdit() {
		var record = getSelect();
		if (!record) return;
		addOrEditNotice(record.data.nid);
	}
	function onDelete() {
		var record = getSelect();
		if (!record) return;
		deleteNotice({
					nid : record.data.nid,
					title : record.data.title
				});
	}
}

function refreshNoticeList() {
	var grid = ui.noticeList;
	var store = grid.getStore();
	store.reload();
}

function deleteNotice(obj) {
	obj = defaultx(obj, 'nid');
	confirmx('您确定要删除公告 [' + obj.nid + '] ' + (obj.title ? '<br />' + obj.title + '<br />' : '')
					+ '吗？', function() {
				ajax({
							url : url.deleteNotice,
							params : {
								nid : obj.nid
							},
							success : function() {
								refreshNoticeList();
								if (obj.success) obj.success();
							}
						});
			});
}
